package models

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"website/appconfig"
)

var DB *gorm.DB

func InitDB() {
	var err error
	mysqlConf := appconfig.Config.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", mysqlConf.User, mysqlConf.Password, mysqlConf.Host, mysqlConf.Port, mysqlConf.Database)
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})

	if err != nil {
		panic(fmt.Errorf("mysql连接失败：Fatal error config file: %s \n", err))
	}
	err = DB.AutoMigrate(&User{}, &News{}, &Records{})
	log.Println("mysql init success")
}
